'use strict';

const Service = require('egg').Service;
const Sequelize = require('sequelize');
const Op = Sequelize.Op;

class RoleService extends Service {
  // 角色列表
  async page(query) {
    const { ctx } = this;
    let config = {
      where:{
        isDel:0
      },
      order:[
        ['createTime', 'DESC']
      ],
      attributes: { exclude: ['power','isDel','delTime'] }
    };
    if(query.name){
      config.where.name = {
        [Op.like]:`%${query.name}%`
      }
    }
    if(!query.pageNO){
      query.pageNO = 1;
    }
    if(!query.pageSize){
      query.pageSize = 10;
    }
    config.offset = (query.pageNO-1)*query.pageSize;
    config.limit = query.pageSize;
    return await ctx.model.Role.findAndCountAll(config);
  }

  // 角色详情
  async detail(query) {
    const { ctx } = this;
    let config = {
      where:{
        isDel:0,
        id:query.id
      },
      attributes: { exclude: ['isDel','delTime'] }
    };
    return await ctx.model.Role.findOne(config);
  }

  // 角色添加
  async add(data){
    const { ctx } = this;
    return await ctx.model.Role.create({
      name:data.name,
      desc:data.desc?data.desc:'',
      power:data.power?data.power.join(','):'',
      createTime:new Date().getTime(),
      updateTime:new Date().getTime(),
      delTime:0
    });
  }

  // 角色编辑
  async edit(data){
    const { ctx } = this;
    return await ctx.model.Role.update({
      name:data.name,
      desc:data.desc?data.desc:'',
      power:data.power?data.power.join(','):'',
      updateTime:new Date().getTime(),
      delTime:0
    },{
      where:{
        id:data.id
      }
    });
  }

  // 角色删除
  async del(data){
    const { ctx } = this;
    return await ctx.model.Role.update({
      isDel:1,
      delTime:new Date().getTime()
    },{
      where:{
        id:data.id
      }
    });
  }

  // 添加/编辑时获取模块集合
  async menuList(){
    const { ctx } = this;
    return await ctx.model.Menu.findAll({
      attributes: { exclude: ['isDel','delTime','createTime','updateTime'] }
    },{
      where:{
        isDel:0
      }
    });
  }

  // 获取角色模块集合
  async roleMenuList(query){
    const { ctx } = this;
    if(query.id==1){
      let config = {
        where:{
          isDel:0
        },
        attributes: { exclude: ['isDel','delTime','createTime','updateTime'] }
      };
      return await ctx.model.Menu.findAll(config);
    }else{
      let config = {
        where:{
          isDel:0,
          id:query.id
        },
        attributes: ['power']
      };
      let result = await ctx.model.Role.findOne(config);
      if(result&&result.power){
        let config = {
          where:{
            isDel:0,
            id: {
              [Op.in]:result.power.split(',')
            }
          },
          attributes: { exclude: ['isDel','delTime','createTime','updateTime'] }
        };
        return await ctx.model.Menu.findAll(config);
      }else{
        return [];
      }
    }
  }
}

module.exports = RoleService;
